/*
 * Created by JFormDesigner on Sun Nov 09 20:02:45 CST 2025
 */

package com.yeban.bams.server;

import com.yeban.bams.entity.Account;
import com.yeban.bams.entity.SavingAccount;
import com.yeban.bams.entity.CreditAccount;
import com.yeban.bams.entity.LoanableSavingsAccount;
import com.yeban.bams.entity.LoanableCreditAccount;

import java.awt.*;
import java.awt.event.*;
import java.util.List;
import javax.swing.*;
import javax.swing.table.*;

/**
 * @author yeban
 */
public class AccountPanel extends JPanel {

    private ATMServer atm;

    public AccountPanel(ATMServer atm) {
        this.atm = atm;
        initComponents();
        initAccountTableModel();
        button1.addActionListener(e -> searchByPersonId());
    }

    private void back(ActionEvent e) {
        atm.dataPanel.reload(); // 进入DataPanel前清空并刷新
        CardLayout cardLayout = (CardLayout) atm.getContentPane().getLayout();
        cardLayout.show(atm.getContentPane(), "dataPanel");
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        dataLabel = new JLabel();
        panel1 = new JPanel();
        backButton = new JButton();
        textField1 = new JTextField();
        button1 = new JButton();
        scrollPane1 = new JScrollPane();
        table1 = new JTable();

        //======== this ========
        setLayout(null);

        //---- dataLabel ----
        dataLabel.setText("\u8d26  \u6237  \u67e5  \u8be2");
        dataLabel.setHorizontalAlignment(SwingConstants.CENTER);
        dataLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 30));
        add(dataLabel);
        dataLabel.setBounds(115, 40, 275, 65);

        //======== panel1 ========
        {
            panel1.setLayout(null);

            {
                // compute preferred size
                Dimension preferredSize = new Dimension();
                for(int i = 0; i < panel1.getComponentCount(); i++) {
                    Rectangle bounds = panel1.getComponent(i).getBounds();
                    preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                    preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
                }
                Insets insets = panel1.getInsets();
                preferredSize.width += insets.right;
                preferredSize.height += insets.bottom;
                panel1.setMinimumSize(preferredSize);
                panel1.setPreferredSize(preferredSize);
            }
        }
        add(panel1);
        panel1.setBounds(new Rectangle(new Point(45, 140), panel1.getPreferredSize()));

        //---- backButton ----
        backButton.setText("\u8fd4\u56de");
        backButton.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
        backButton.addActionListener(e -> back(e));
        add(backButton);
        backButton.setBounds(370, 550, 100, 45);
        add(textField1);
        textField1.setBounds(110, 110, 185, 40);

        //---- button1 ----
        button1.setText("\u67e5  \u8be2");
        button1.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
        add(button1);
        button1.setBounds(305, 110, 90, 40);

        //======== scrollPane1 ========
        {

            //---- table1 ----
            table1.setModel(new DefaultTableModel(
                new Object[][] {
                    {null, null, null, null, null},
                    {null, null, null, null, null},
                    {null, null, null, null, null},
                    {null, null, null, null, null},
                },
                new String[] {
                    "\u8d26\u6237", "\u8d26\u6237\u7c7b\u578b", "\u4f59\u989d", "\u900f\u652f\u989d\u5ea6", "\u8d37\u6b3e\u989d"
                }
            ));
            scrollPane1.setViewportView(table1);
        }
        add(scrollPane1);
        scrollPane1.setBounds(70, 160, 375, 375);

        setPreferredSize(new Dimension(500, 650));
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JLabel dataLabel;
    private JPanel panel1;
    private JButton backButton;
    private JTextField textField1;
    private JButton button1;
    private JScrollPane scrollPane1;
    private JTable table1;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on

    // 设置账户表结构（不可编辑）
    private void initAccountTableModel() {
        table1.setModel(new DefaultTableModel(
                new Object[]{"账户", "账户类型", "余额", "透支额度", "贷款额"}, 0
        ) {
            @Override public boolean isCellEditable(int row, int column) { return false; }
        });
    }

    // 根据身份证号加载该身份证下的所有账户信息
    public void loadAccountsByPersonId(String personId) {
        textField1.setText(personId);
        DefaultTableModel model = (DefaultTableModel) table1.getModel();
        model.setRowCount(0);

        List<Account> accounts = atm.bank.getAccountsByPersonId(personId);
        for (Account acc : accounts) {
            String typeText;
            String ceilingText = "--";
            String loanText = "--";

            if (acc instanceof LoanableCreditAccount) {
                typeText = "可贷款信用账户";
                ceilingText = String.format("%.2f", ((CreditAccount) acc).getCeiling());
                loanText = String.valueOf(((LoanableCreditAccount) acc).getLoanAmount());
            } else if (acc instanceof CreditAccount) {
                typeText = "信用账户";
                ceilingText = String.format("%.2f", ((CreditAccount) acc).getCeiling());
            } else if (acc instanceof LoanableSavingsAccount) {
                typeText = "可贷款储蓄账户";
                loanText = String.valueOf(((LoanableSavingsAccount) acc).getLoanAmount());
            } else if (acc instanceof SavingAccount) {
                typeText = "储蓄账户";
            } else {
                typeText = "未知类型";
            }

            model.addRow(new Object[]{
                    acc.getId(),
                    typeText,
                    String.format("%.2f", acc.getBalance()),
                    ceilingText,
                    loanText
            });
        }
    }

    // 点击“查询”按钮时，按输入框身份证号查询
    private void searchByPersonId() {
        String personId = textField1.getText();
        if (personId != null && !personId.trim().isEmpty()) {
            loadAccountsByPersonId(personId.trim());
        }
    }

    // 清空页面
    public void clear() {
        textField1.setText("");
        DefaultTableModel model = (DefaultTableModel) table1.getModel();
        model.setRowCount(0);
    }
}
